local skynet = require "skynet"
require "skynet.manager"	-- import skynet.register
local clientReady = {}
local playerName = {}
local playerStatus = {}
local playerPos = {}
local playerRot = {}
local playerMovement = {}

local command = {}

local players = {}
local name2id = {}

local max_actor_id = 0

-- function command.DEAD(id)
-- 	playerStatus[id] = "dead"
-- end

-- function command.REMOVE(id)
-- 	local name = playerName[id]
-- 	clientReady[id] = nil
-- 	playerName[id] = nil
-- 	playerStatus[id] = nil
-- 	playerPos[id] = nil
-- 	playerRot[id] = nil
-- 	playerMovement[id] = nil
-- 	return name
-- end

-- function command.GETCLIENTREADY()
-- 	return clientReady
-- end

-- function command.UPDATE_PLAYER(id, key, value)
-- 	if players[id] then
-- 		players[id][key] = value
-- 	end
-- end

-- function command.GET_PLAYERS()
-- 	local online_players = {}
-- 	for i,player in pairs(players) do
-- 		skynet.error("player["..i .."] online:"..tostring(player.online).." Naming "..player.name)
-- 		if players[i].online then
-- 			skynet.error("Yes is true")
-- 			-- +1 to prevent from using 0 index
-- 			online_players[i+1] = player
-- 		end
-- 	end
-- 	return online_players
-- end

-- function command.GET_PLAYER(id)
-- 	if players[id] then
-- 		return players[id]
-- 	end
-- 	return nil
-- end

function command.READY(player_name)
	local player_id = name2id[player_name]
	if player_id then
		if players[player_id].online then
			return -1	--用户已经登陆
		end
	end

	if player_id == nil then
		--产生一个新ID
		player_id = max_actor_id
		max_actor_id=max_actor_id+1
		name2id[player_name] = player_id
		print(">>>>>>>>>>>>>>")
		print(player_id, max_actor_id)

		local player = {
			id = player_id, 
			name = player_name, 
		}

		for i,v in pairs(player) do
			print(i,v)
		end
		players[player_id] = player
	end

	return player_id
end


-- function command.LOGOUT(player_id)
-- 	skynet.error("logout:"..player_id)
-- 	if players[player_id] then
-- 		skynet.error("online:"..tostring(players[player_id].online))
-- 		players[player_id].online = false
-- 		skynet.error("online:"..tostring(players[player_id].online))
-- 	end

-- 	for id,player in pairs(players) do
-- 		skynet.error("player["..id .."] online:"..tostring(player.online))
-- 	end

-- end
skynet.start(function()
	skynet.dispatch("lua", function(session, address, cmd, ...)
		cmd = cmd:upper()
		if cmd == "PING" then
			assert(session == 0)
			local str = (...)
			if #str > 20 then
				str = str:sub(1,20) .. "...(" .. #str .. ")"
			end
			skynet.error(string.format("%s ping %s", skynet.address(address), str))
			return
		end
		local f = command[cmd]
		if f then
			skynet.ret(skynet.pack(f(...)))
		else
			error(string.format("Unknown command %s", tostring(cmd)))
		end
	end)
--	skynet.traceproto("lua", false)	-- true off tracelog
	skynet.register "SIMPLEDB"
end)